var packInfoTable = function() {
	return {
		init: function(pkId, colId) {
			monitorDetailCount = 0;
			
			$("#form_colClientId").text(colId);
			$("#pkId").val(pkId);
			
			//自动刷新周期
			var cycle;
			$.ajax({
				"type" : "post",
				"url" : "main/sysDictIndex/getDictByParentKey.mvc",
				"async" : false,
				"dataType" : "json",
				"data" : {
					"parentKey" : 'REFRESH_CYCLE'
				},
				"success" : function(resp) {
					if(resp.dict.length!=0){
						cycle = resp.dict[0].dictKey;
					}else {
						cycle = 5000;
					}
				}
			});
			getSerialNo();
			setPackInfo();
			monitorRefreshTimer = setInterval(setPackInfo, cycle);
			
			//获取序列号
			function getSerialNo() {
				$.ajax({
					"type" : "post",
					"url" : "main/packRegMng/getSerialNoList.mvc",
					"dataType" : "json",
					"data" : {
						
					},
					"success" : function(resp) {
						//页面赋值
						var codeArray = new Array();
						var sNo = resp.data;
						for (var i = 0; i< sNo.length; i++) {
							var temp = {};
							temp.key = sNo[i].serialNo;
							temp.value = sNo[i].serialNo;
							codeArray.push(temp);
						}
						util.setOption(codeArray, "form_pack_code");
						$("#form_pack_code").select2({
			          	     placeholder:'请选择',//默认文字提示
			          	     language: "zh-CN",//汉化
			          	     allowClear: true//允许清空
			          	});
					}
				});
			};
			
			//设置电池信息
			function setPackInfo () {
				App.blockUI($("#regInfoDiv"));
				var d = {};
				d['colClientId'] = colId;
				var pCode = $("#form_pack_code").val();
				//查询电池详情并赋值
				$.ajax({
					"type" : "post",
					"url" : "main/packRegMng/getRegPackDetail.mvc",
					"dataType" : "json",
					"data" : {
						"colClientId" : colId,
						"packCode" : pCode
					},
					"success" : function(resp) {
						//页面赋值
						var packCur = resp.baseInfo;
						if (packCur) {
							$("span[id^='info_']").each(function(e){
								var id=$(this).attr("id");
								var idStr = id.substr(5);
								$("#" + id).empty();
								eval("$('#" + id + "').append(packCur." +idStr + ")");
							});
						} else {
							$("span[id^='info_']").each(function(e){
								var id=$(this).attr("id");
								$("#" + id).empty();
							});
						}
						createTableList(resp.group);
						App.unblockUI($("#regInfoDiv"));
					},
					error:function(e){
						App.unblockUI($("#regInfoDiv"));//停止loading
						rmsBox.notify('error', {msg: '出错了！',delay:3000});
					}
				});
			};
			
			/**
			 * 生成电压和温度动态表格
			 * @param group 电压&温度 data
			 * @returns
			 */
			function createTableList(group){
				$("#real_time_info").empty();
				var groupNo = "";
				var type = "";
				var tableId = "";
				var index=0;
				for (var i=0;i<group.length;i++) {
					if (groupNo != group[i].groupNo || type != group[i].type){
						//new table
						index = index + 1;
						groupNo = group[i].groupNo;
						type = group[i].type;
						tableId = "info_table" + index;
						$("#real_time_info").append("<li id='" + tableId + "'></li>");
						if (type == '1') {
							//电压
							$("#" + tableId).append("<p class='c-red c-bold'><span class='fl-left'></span>蓄电池模块号："
									+ groupNo + "&nbsp;电压（V）<span class='fl-right'></span></p><table class='table table-bordered'><tr class='tdHead'></tr><tr class='tdData'></tr></table>");
						} else {
							$("#" + tableId).append("<p class='c-red c-bold'><span class='fl-left'></span>蓄电池模块号："
									+ groupNo + "&nbsp;采样点温度（℃）<span class='fl-right'></span></p><table class='table table-bordered'><tr class='tdHead'></tr><tr class='tdData'></tr></table>");
						}
					}
					if (type == '1'){
						$("#" + tableId + " .tdHead").append("<th>" + group[i].groupCoreNo + "号电压</th>");
						$("#" + tableId + " .tdData").append("<td>" + group[i].data + "</td>");
					} else {
						$("#" + tableId + " .tdHead").append("<th>" + group[i].groupCoreNo + "号采样点温度</th>");
						$("#" + tableId + " .tdData").append("<td>" + group[i].data + "</td>");
					}
				}
			};
			
			/**
			 * 弹出客户选择窗口
			 */
			$("#form_cusName").click(function(e){
				//先重置查询条件
				$("#customer_reset").click();
				$("#select-customer").modal("show");
				var table = $('#customer_table').DataTable();
				table.draw(true);
			});
			
			$(function(){
				util.getOption("main/packModel/getPackModelList.mvc", null, "form_pack_model");
				$("#form_pack_model").select2({
	          	     placeholder:'请选择',//默认文字提示
	          	     language: "zh-CN",//汉化
	          	     allowClear: true//允许清空
	          	});
			});
		}
	}
}();

var customerTable = function (){
	return {
		init:function() {
			util.initCheckBox("customer_table");
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "cusCode",
					"value" : $("#cus_cusCode").val().trim()
				});
				aoData.push({
					"name" : "cusName",
					"value" : $("#cus_cusName").val().trim()
				});
				aoData.push({
					"name" : "province",
					"value" : $("#loc_province").val()
				});
				aoData.push({
					"name" : "city",
					"value" : $("#loc_city").val()
				});
				aoData.push({
					"name" : "area",
					"value" : $("#county").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			$('#customer_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/customer/getCustomer.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ {
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return '<div class="radio"><span><input type="radio" class="checkboxes"/></span></div>';
					},
					"bSortable" : false
				},
				{
					"data" : "cusCode",
					"bSortable" : false,
					"defaultContent": ""
				}, 
				{
					"data" : "cusName",
					"bSortable" : false,
					"defaultContent": ""
				}, 
				{
					"data" : "shortName",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "city",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "province",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "impLevel",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "type",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "status",
					"bSortable" : false,
					"render" : function(data, type, full, meta) { 
						if("试用"==data){
							return "<span class=\"label label-success\">"+data+"</span>";
						}else if("潜在"==data){
							return "<span class=\"label label-info\">"+data+"</span>";
						} else if("高意向"==data) {
							return "<span class=\"label label-important\">"+data+"</span>";
						} else if("成交"==data) {
							return "<span class=\"label\">"+data+"</span>";
						} else {
							return null;
						}
					},
					"defaultContent": ""
				}]
			});
			
			//客户查询
			$("#query_customer_btn").click(function(e) {
				var table = $('#customer_table').DataTable();
				table.draw(true);
			});
			
			//重置
			$("#customer_reset").click(function() {
				$("#customer_form")[0].reset();
				$("#cityDiv").citySelect({
					nodata: "none",
					required: false,
					prov:"",
					city:"",
					dist:""
				}); 
			});
			//确定
			$("#customer_selected").click(function() {
				var d = [];
				d = util.getCheckedData("customer_table");
				if (d.length != 1) {
					util.showModal("#_alertModal", '请选择一条记录！');
					return false;
				}
				$("#form_customId").val(d[0].pkId);
				$("#form_cusName").val(d[0].cusName);
				//清除选项
				$("#select_customer_close").click();
			});
			
			$(function(){
				$('.search-box input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('#query_customer_btn').click();
					}
				});
			});
		}
	}
}();

/**
 * 注册并打印按钮
 */
$("#register").click(function(){
	var d={};
	var packCode = $("#form_pack_code").val();
	var colClientId = $("#form_colClientId").text();
	var simPhoneno = $("#form_sim_phoneno").val();
	var packModel = $("#form_pack_model").val();
	var customId = $("#form_customId").val();
	var id = $("#pkId").val();
	if (packCode == '') {
		util.showModal("#_alertModal", '请选择电池ID！');
		return;
	} else if(colClientId == '') {
		util.showModal("#_alertModal", '无采集终端ID，请刷新后重试！');
		return;
	} else if (packModel == '') {
		util.showModal("#_alertModal", '请选择电池系统型号！');
		return;
	} else if (simPhoneno == '') {
		util.showModal("#_alertModal", '请输入手机号码！');
		return;
	} else if (!/1[3584]\d{9}$/.test(simPhoneno)) {
		util.showModal("#_alertModal", '请填写正确的手机号！');
		return;
	} else if (customId == '') {
		util.showModal("#_alertModal", '请选择客户！');
		return;
	}
	d['packCode'] = packCode;
	d['colClientId'] = colClientId;
	d['simPhoneno'] = simPhoneno;
	d['packModel'] = packModel;
	d['customId'] = customId;
	d['pkId'] = id;
	$.ajax({
		"type" : "post",
		"url" : "main/packRegMng/registerPack.mvc",
		"dataType" : "json",
		"data" : {
			"record" : JSON.stringify(d)
		},
		"success" : function(resp) {
			if(resp.msg=='error') {
				util.alertMsg("提示", "数据异常！");
				return;
			} else if (resp.msg == 'expire'){
				util.alertMsg("提示", "数据已过期，请刷新后重试！");
				return;
			} else {
				rmsBox.notify('success', {msg: '注册成功！'});
				setTimeout(function(e) {
					$('#print_btn').click();
					if ($('#print_btn').attr("href")) {
						$("#print_colClientId").html(colClientId);
						$("#print_packNum").html(packCode);
						$("#print_cusName").html($("#form_cusName").val());
					} else {
						$('#print_btn').attr("href", "#dayin");
						$('#print_btn').click();
					}
				}, 1000);
			}
		}
	});
});

//确认打印
$("#print_confirm").click(function(e){
	util.showContent("pages/basic/packRegMng.jsp");
	$("#print_area").jqprint();
});

//取消打印
$("#print_close").click(function(e){
	util.showContent("pages/basic/packRegMng.jsp");
});
